package cn.edu.flink.tutorial.wc;

import lombok.SneakyThrows;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StreamWordCount {
    @SneakyThrows
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();

//        DataStreamSource<String> textDSS = env.socketTextStream("localhost", 8080);
        DataStreamSource<String> textDSS = env.readTextFile("input/word.txt");

        SingleOutputStreamOperator<Tuple2<String, Long>> wordAndOne = textDSS.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                        for (String word : s.split(" ")) {
                            collector.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );

        SingleOutputStreamOperator<Tuple2<String, Long>> sum = wordAndOne
                .keyBy(t -> t.f0)
                .sum(1);

        sum.print();

        env.execute("WordCount");
    }
}
